import { objToQueryString } from "./object";

export class Router {
  static navigateTo(
    url: string,
    success?: (resp: UniApp.NavigateToSuccessOptions) => void
  ) {
    uni.navigateTo({ url: getPushPath(url), success });
  }

  static redirectTo(url: string) {
    uni.redirectTo({ url: getPushPath(url) });
  }

  static navigateToOrRedirectTo(isReplace: boolean, url: string) {
    isReplace ? Router.redirectTo(url) : Router.navigateTo(url);
  }

  static navigateBack(delta = 1, success?: () => void) {
    uni.navigateBack({ delta, success });
  }

  static switchTab(url: string) {
    uni.switchTab({ url });
  }

  static reLaunch(url: string) {
    uni.reLaunch({ url: getPushPath(url) });
  }

  static navigateToMiniProgram(appId: string, path?: string) {
    uni.navigateToMiniProgram({ appId, path });
  }

  static dataToQuery(data: any, encode = true) {
    return objToQueryString(data, encode);
  }

  static navigateToWeb(url: string, share = "0") {
    uni.navigateTo({
      url: `/pages/web/index?url=${encodeURIComponent(url)}&share=${share}`,
    });
  }
}
/**
 * 解析跳转url，返回真实跳转链接
 * @param url
 */
const getPushPath = (url: string) => {
  let path = "";
  if (url.startsWith("http")) {
    // 普通网页链接
    path += `/pages/web/index?url=${encodeURIComponent(url)}`;
  } else if (url.startsWith("smyglobal://") || url.startsWith("smy://")) {
    // App deeplink
    path = getAppPath(url);
  } else {
    path = url;
  }
  return path;
};

/**
 * 解析App deeplink，返回真实跳转链接
 * @param url
 */
const getAppPath = (url: string) => {
  const [path, query] = url
    .replace("smyglobal://", "")
    .replace("smy://", "")
    .split("?");
  return path === "course/album"
    ? `/package/study/pages/course/detail?${query}`
    : "";
};
